package com.gjintel.business.proj.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gjintel.business.proj.model.ProjectBidInfo;
import com.gjintel.business.proj.model.ProjectInfo;
import com.gjintel.business.proj.model.ProjectPause;
import com.gjintel.business.proj.service.IProjectBidService;
import com.gjintel.business.proj.service.IProjectInfoService;
import com.gjintel.business.proj.service.IProjectPauseService;
import com.gjintel.business.proj.service.impl.NotifyServiceImpl;
import com.gjintel.business.webcontent.model.WebContent;
import com.gjintel.business.webcontent.service.IWebContentService;
import com.gjintel.framework.common.service.IDepositExecuteService;
import com.gjintel.framework.common.service.IDepositService;
import com.gjintel.framework.constant.ActivitiMap;
import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.constant.ProjectStatus;
import com.gjintel.framework.dataset.model.DataSet;
import com.gjintel.framework.dataset.service.IDataSetService;
import com.gjintel.framework.dict.model.Dictionary;
import com.gjintel.framework.holidayset.service.IHolidaySetService;
import com.gjintel.framework.log.model.LogInfo;
import com.gjintel.framework.log.util.LogUtil;
import com.gjintel.framework.log.util.LogUtil.LogType;
import com.gjintel.framework.projecttype.model.ProjectType;
import com.gjintel.framework.projecttype.service.IProjectTypeService;
import com.gjintel.framework.register.model.RegisterUser;
import com.gjintel.framework.register.service.IRegisterUserService;
import com.gjintel.framework.res.model.Resources;
import com.gjintel.framework.role.model.ProjectOperation;
import com.gjintel.framework.role.model.Role;
import com.gjintel.framework.role.service.IRoleService;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.user.model.UserRole;
import com.gjintel.framework.user.service.IUserService;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.framework.util.DictUtil;
import com.gjintel.framework.util.FileResUtil;
import com.gjintel.framework.util.dto.Bank;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.dao.Sort;
import com.gjintel.sdk.util.BatchZipDownload;
import com.gjintel.sdk.util.DateUtils;
import com.gjintel.sdk.util.StringUtil;
import com.gjintel.sdk.util.WordHandler;
import com.gjintel.workflow.trade.dto.ProcessInstanceAndHistoryDto;
import com.gjintel.workflow.trade.service.IWorkflowProcessInstanceService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 采购不评标项目Controller
 * @author wwang
 */
@RequestMapping("/business/projectNb")
@Controller
public class ProjectNBController {
	
	@SuppressWarnings("unused")
	private static final Logger LOG = Logger.getLogger(ProjectController.class);

	@Autowired
	private IProjectInfoService projectInfoService;

	@Autowired
	private IWorkflowProcessInstanceService workflowProcessInstanceService;

	@Autowired
	private IRoleService roleService;

	@Autowired
	private IProjectPauseService profectPauseService;
	
	@Autowired
	private IHolidaySetService holidaySetService;
	
	@Autowired
	private IProjectBidService projectBidService;

	@Autowired
	private IDataSetService dataSetService;
	
	@Autowired
	private IProjectTypeService projectTypeService;
	
	@Autowired
	private IDepositService depositService;
	
	@Autowired
	private NotifyServiceImpl notifyService;
	
	@Autowired
	private IRegisterUserService registerUserService;
	
	@Autowired
	private IDepositExecuteService depositExecuteService;

	@Autowired
	private IUserService userService;

	@Autowired
	private TaskService taskService;

	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private IWebContentService webContentService;


	/**
	 * 不评标流程key
	 */
	private static final String PROCESS_NOBID_KEY="tender_nobid";

	/** 编制审核通过7*/
	private static final Integer COMPILEAUDITPASS = 7;

	/** 编制审核不通过25*/
	private static final Integer COMPILEAUDITNPASS = 25;

	/**
	 * 系统最低价中标单位0
	 */
	private static final Integer SYSTEMCHOICE = 3;
	
	/**
	 * 采购人选择中标单位1
	 */
	private static final Integer BUYERCHOICE = 1;
	/**
	 * 采购人选择流标2
	 */
	private static final Integer BUYER_FLOW_DOWN = 2;


	/** 竞价公示暂停 */
	private String BID_PAUSE = "101";
	/** 中标公示暂停 */
	private String HIT_PAUSE = "102";
	/** 质疑投诉 */
	private String OPPUGN_PAUSE = "103";
	/** 变更公告 */
	private String EDITPUBLISH = "104";

	
	/**
	 * 项目审核列表
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("centerAuditor/project")
	public ModelAndView audit(HttpSession session) {
		ModelAndView mv = new ModelAndView("/projNB/center-auditor/project");
		// 获取项目类型
		List<ProjectType> projectTypeList = projectTypeService.findAll();
		mv.addObject("projectTypeList", projectTypeList);
		return mv;
	}
	
	/**
	 * @description 项目列表
	 * @author wei
	 * @date 2016-8-16
	 * @param session
	 * @param project
	 * @param page
	 * @param sort
	 * @param startTime
	 *            创建开始时间
	 * @param stopTime
	 *            创建结束时间
	 * @param bidTime
	 *            开标开始时间
	 * @param bidStopTime
	 *            开标结束时间
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public JSONObject list(HttpSession session, ProjectInfo project, Page page, Sort sort, java.sql.Date startTime,
			java.sql.Date stopTime, java.sql.Date bidTime, java.sql.Date bidStopTime, String roleId) {
		long sTime = System.currentTimeMillis(); // 获取开始时间
		long eTime = 0;
		User user = (User) session.getAttribute("loginUser");
		// 结束时间处理，加一天
		stopTime = StringUtil.addOneDayDate(stopTime, 1);
		bidStopTime = StringUtil.addOneDayDate(bidStopTime, 1);
		String _processIds = "";
		String _filter = null;
		//增加保证金筛选
		if(project.getExecutePromissFilter()!=null && project.getExecutePromissFilter().equals(Constant.UNPAY_EXECUTE_UNRETURN)){
		     //未交履约保证金未退
			project.setReturnDepositFlag(false);
			project.setStatusExecutePromiss(0);
			
		}else if (project.getExecutePromissFilter()!=null && project.getExecutePromissFilter().equals(Constant.PAY_EXECUTE_UNRETURN)){
			//已交履约保证金未退
			project.setReturnDepositFlag(false);
			project.setStatusExecutePromiss(1);
		}else if(project.getExecutePromissFilter()!=null && project.getExecutePromissFilter().equals(Constant.PAY_EXECUTE_RETURN)){
			//已交履约保证金已退
			project.setReturnDepositFlag(true);
			project.setStatusExecutePromiss(1);
		}else if(project.getExecutePromissFilter()!=null && project.getExecutePromissFilter().equals(Constant.ALL_DEPOSIT_RETURN)){
			//履约保证金已退(全退)
			project.setReturnDepositFlag(true);
			project.setStatusExecutePromiss(2);
		}
		

		// 增加流程id的过滤：如果角色不是指定的“超级管理员，业务管理员、监督员、系统管理员“等 ，则取出processId过滤.
		// TODO:数据量较大时要考虑性能问题（可考虑增加时间过滤)
		if (!"bizmanager".equals(roleId)// 业务管理员页面
				&& !"administrator".equals(roleId)// 系统管理员页面
				&& !"supervisor".equals(roleId)// 监督员页面
			    && !"finance".equals(roleId)){//财务管理员页面
				//&&!"centerAuditor".equals(roleId))//中心审核人

			List<ProcessInstanceAndHistoryDto> processInstanceList = workflowProcessInstanceService
					.findProcessInstanceAndHistoryList(PROCESS_NOBID_KEY, user.getId(), roleId);
			eTime = System.currentTimeMillis(); // 获取结束时间
			for (ProcessInstanceAndHistoryDto dto : processInstanceList) {
				_processIds += "'" + dto.getBusinessKey() + "',";
			}
			if (_processIds.length() > 0) {
				_processIds = _processIds.substring(0, _processIds.length() - 1);
			}
			_filter = _processIds;
		}
		
		 //数据填充到page
		project.setAuditable(null);
		this.projectInfoService.findAllByIds(_filter, project, page, sort, startTime, stopTime, bidTime, bidStopTime,
				null, null);

		// 获取用户所以角色ids
		String roleIds = "";
		List<Role> roleList = roleService.findRolesByUserId(user.getId());
		for (Role role : roleList) {
			roleIds += "'" + role.getId() + "',";
		}
		if (roleIds.length() > 0) {
			roleIds = roleIds.substring(0, roleIds.length() - 1);
		}

		List<ProjectInfo> pageList = page.getResult();
		for (ProjectInfo pro : pageList) {
			Dictionary dicProStatus = DictUtil.dict("proj_status", pro.getStatus() + "");
			if (dicProStatus != null) {
				pro.setStatusName(dicProStatus.getName());// 项目状态
			} else {
				pro.setStatusName("未知");// 项目状态
			}

			//************************** BEGIN: 取出操作菜单列表，循环组合为html
			StringBuffer _sbOpera = new StringBuffer("");
			List<ProjectOperation> list = roleService.findOperationByRoleIdAndStatus(roleIds, pro.getStatus() + "",PROCESS_NOBID_KEY);// 数据库中取
			// 缓存中取
			// List<ProjectOperation> list =
			// InitCacheData.getInstance().getCacheOperationData(CacheType.PROJ_OPERATION).get(ActivitiMap.getProperty(roleId)).get(pro.getStatus()+"");
			int opCount=1;//操作菜单的数量
			for (ProjectOperation op : list) {
				if (op.getRoleId().equals(ActivitiMap.getProperty(roleId))) {								
					 if (op.getOperaName().equals("退还保证金")) {						
							if(pro.getReturnDepositFlag()!=true){
								_sbOpera.append( op.getActionUrl().replace("row.id", pro.getId()) + (opCount%3==0?"<br/>":""));
							}
					 }
					 else if (op.getOperaName().equals("退还履约保证金")) {
						    	 boolean showReturnFlag =this.excuteDepositButtionByProjectStatus(pro.getStatus()); 
							if(pro.getFinishExecuteDesposit()!=1 && showReturnFlag==true){
								_sbOpera.append( op.getActionUrl().replace("row.id", pro.getId()) + (opCount%3==0?"<br/>":""));
							} 
					 }
					 else if(op.getId().equals(Constant.BIDDING_PAUSE_BUTTON)){//竞价公示暂停
						    List<ProjectPause> pauselist=profectPauseService.getWorkingProjectPause(Constant.BIDDING_PAUSE, pro.getId());
							if(pauselist.size()<1){
								_sbOpera.append(op.getActionUrl().replace("row.id", pro.getId()) + (opCount%3==0?"<br/>":""));
							}else if(pauselist.get(0).getResult().equals("2")||pauselist.get(0).getResult().equals("3")){
								_sbOpera.append( op.getActionUrl().replace("row.id", pro.getId()) + (opCount%3==0?"<br/>":""));
							}
					}else if(op.getId().equals(Constant.WIN_BIDDING_SHOW_PAUSE_BUTTON)){//中标公示暂停
						    List<ProjectPause> pauselist=profectPauseService.getWorkingProjectPause(Constant.WIN_BIDDING_SHOW_PAUSE, pro.getId());
							if(pauselist.size()<1){
								_sbOpera.append( op.getActionUrl().replace("row.id", pro.getId()) + (opCount%3==0?"<br/>":"") );
							}else if(pauselist.get(0).getResult().equals("2")||pauselist.get(0).getResult().equals("3")){
								_sbOpera.append( op.getActionUrl().replace("row.id", pro.getId()) + (opCount%3==0?"<br/>":""));
							}
					}
					else if(op.getId().equals(Constant.BIDDING_PAUSE_BUTTON_NB)){//竞价公示暂停(不评标)
					    List<ProjectPause> pauselist=profectPauseService.getWorkingProjectPause(Constant.BIDDING_PAUSE, pro.getId());
						if(pauselist.size()<1){
							_sbOpera.append(op.getActionUrl().replace("row.id", pro.getId()) + (opCount%3==0?"<br/>":""));
						}else if(pauselist.get(0).getResult().equals("2")||pauselist.get(0).getResult().equals("3")){
							_sbOpera.append( op.getActionUrl().replace("row.id", pro.getId()) + (opCount%3==0?"<br/>":""));
						}
					 }
					else if(op.getId().equals(Constant.WIN_BIDDING_SHOW_PAUSE_BUTTON_NB)){//中标公示暂停(不评标)
						    List<ProjectPause> pauselist=profectPauseService.getWorkingProjectPause(Constant.WIN_BIDDING_SHOW_PAUSE, pro.getId());
							if(pauselist.size()<1){
								_sbOpera.append( op.getActionUrl().replace("row.id", pro.getId()) + (opCount%3==0?"<br/>":"") );
							}else if(pauselist.get(0).getResult().equals("2")||pauselist.get(0).getResult().equals("3")){
								_sbOpera.append( op.getActionUrl().replace("row.id", pro.getId()) + (opCount%3==0?"<br/>":""));
							}
					}else {
							_sbOpera.append( op.getActionUrl().replace("row.id", pro.getId()) + (opCount%3==0?"<br/>":""));
					}
					 opCount++;
				}
			}//************************** END: 取出操作菜单列表，循环组合为html

			if ("bizmanager".equals(roleId)) {// 列表页面是业务管理员列表页面时
				// 终止
				UserRole ur = roleService.findUserRole(ActivitiMap.BIZMANAGER_ID, user.getId());
				if (ur != null && pro.getStatus() != Integer.valueOf(ProjectStatus.CANCEL.toString())// 撤销
																										// 不显示终止操作菜单
						&& pro.getStatus() != Integer.valueOf(ProjectStatus.PROJ_OVER.toString())// 结项
																									// 不显示终止操作菜单
						&& pro.getStatus() != Integer.valueOf(ProjectStatus.FLOW_DOWN.toString())// 流标
																									// 不显示终止操作菜单
						&& pro.getStatus() != Integer.valueOf(ProjectStatus.SHOWING_FLOW.toString())) {// 流标公示
																										// 不显示终止操作菜单
					_sbOpera.append(Constant.CANCLE_PROJECT.replace("row.id", pro.getId()));
				}
				
				//添加 查看资料 操作(任何状态下)
				_sbOpera.append(Constant.VIEWFILE_OPERATION.replace("row.id", pro.getId()));
			}
			
			// 系统管理员
			if ("administrator".equals(roleId)) {// 列表页面是系统管理员列表页面时
				UserRole adminUr = roleService.findUserRole(ActivitiMap.ADMINISTRATOR_ID, user.getId());
				if (adminUr != null && isCodeEdit(pro.getStatus())) {
					// 添加变更项目编号
					_sbOpera.append(Constant.EDITPROJECTCODE_OPERATION.replace("row.id", pro.getId()));
				}
			}
			
			// 监督员
			if ("supervisor".equals(roleId)) {// 列表页面是监督员列表页面时
				UserRole adminUr = roleService.findUserRole(ActivitiMap.SUPERVISOR_ID, user.getId());
			}

			// 添加项目详情操作
			_sbOpera.append(Constant.DETAILS_OPERATION.replace("row.id", pro.getId()));
			pro.setOperation(_sbOpera.toString());
		}

		System.err.println("++++++++++++++++++++++++ 耗时： " + (eTime - sTime));

		return CommUtil.getPageJSONData(page, true);
	}
	
	/**
	 * @description 判断退还履约保证按钮出现状态是否在列举的状态中存在
	 * @author shy
	 * @date 2016年12月23日
	 */
	private boolean excuteDepositButtionByProjectStatus(Integer status) {
		List<Integer> list = new ArrayList<Integer>();
		list.addAll(Arrays.asList(Integer.valueOf(ProjectStatus.WAIT_PROJ_OVER_SURE.toString()), // 结项
				Integer.valueOf(ProjectStatus.PROJ_OVER.toString()), // 项目结束
				Integer.valueOf(ProjectStatus.CANCEL.toString())));// 撤销
		return list.contains(status);
	}
	
	/**
	 * @description 是否在分配阶段之后，采购人确认之前
	 * @author wwang
	 * @date 2016年9月18日
	 */
	private boolean isCodeEdit(Integer status) {
		List<Integer> list = new ArrayList<Integer>();
		list.addAll(Arrays.asList(Integer.valueOf(ProjectStatus.WAIT_COMPILE.toString()),
				Integer.valueOf(ProjectStatus.WAIT_SURE.toString())//
				, Integer.valueOf(ProjectStatus.BUY_NOT_PASS.toString()),
				Integer.valueOf(ProjectStatus.OVER_TIME.toString())));
		return list.contains(status);
	}
	
	
	/**
	 * 编制页面
	 * 
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/buyer/compileInput")
	public ModelAndView compileInput(String projectId) {
		ModelAndView mv = new ModelAndView("/projNB/buyer/compile-goods-input");

		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);

		if (Constant.PROJECTCATAGORY_GOODSID.equals(project.getCatagoryId())) {// 货物类
			mv.setViewName("/projNB/buyer/compile-input/compile-goods-input");
		} else if (Constant.PROJECTCATAGORY_SERVICEID.equals(project.getCatagoryId())) {// 服务类
			mv.setViewName("/projNB/buyer/compile-input/compile-service-input");
		} else if (Constant.PROJECTCATAGORY_ENGINEERINGID.equals(project.getCatagoryId())) {// 工程类
			mv.setViewName("/projNB/buyer/compile-input/compile-engineering-input");
		} else if (Constant.PROJECTCATAGORY_PROPERTYID.equals(project.getCatagoryId())) {// 产权类
			// TODO 产权类的编制页面
			mv.setViewName("/projNB/buyer/compile-input");
		}
		
		// 默认编制审核确认时间当天的两个工作日
		Date buyerSureTime = this.holidaySetService.getWorkDayByDays(new Date(), 2);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		List<Resources> resList = FileResUtil.findResources(project.getId());
		mv.addObject("resList", resList);
		mv.addObject("project", project);
		mv.addObject("buyerSureTime", sdf.format(buyerSureTime));
		return mv;
	}
	
	/**
	 * 项目编制提交
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/buyer/doSubmitCompile")
	@ResponseBody
	public String doSubmitCompile(HttpSession session, HttpServletRequest request, ProjectInfo project,
			String bidStartDateStr, String bidStartTimeStr
			, String qualifyFromDateStr, String qualifyEndDateStr
			,String afterAuditDateStr,String afterAuditTimeStr,
			String budgetMenuData, String replyContent) throws Exception {
		User user = (User) session.getAttribute("loginUser");

		//确认时间早于服务器当前时间
		if(!new Date().before(project.getValidTime())){
			return "overConfirmDate";
		}

		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, project.getId());
		
		//编制提交  保存开标时间
		// 开标时间处理
		Date bidStartTime = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (bidStartDateStr != null && !bidStartDateStr.isEmpty()&&bidStartTimeStr!=null&&!bidStartTimeStr.isEmpty()) {
			String bidStartStr = bidStartDateStr + " " + bidStartTimeStr + ":00:00";
			bidStartTime = StringUtil.StringToDate(bidStartStr);
		}
		
		// 资质后审时间处理
		Date afterAuditDate = null;
		if (afterAuditDateStr != null && !afterAuditDateStr.isEmpty()) {
			String afterAuditStr = afterAuditDateStr + " " + afterAuditTimeStr + ":00:00";
			afterAuditDate = StringUtil.StringToDate(afterAuditStr);
		}

		// ==================
		// 保存项目信息
		pro.setBidStartTime(bidStartTime);
		pro.setDeliveryPoint(project.getDeliveryPoint());
		pro.setDeliveryLimit(project.getDeliveryLimit());
		pro.setPromissMoney(project.getPromissMoney());
		pro.setManageRoom(project.getManageRoom());
		pro.setQualifyFromDate(project.getQualifyFromDate());
		pro.setQualifyEndDate(project.getQualifyEndDate());
		pro.setValidTime(project.getValidTime());
		if (qualifyFromDateStr != null && !qualifyFromDateStr.isEmpty()) {
			pro.setQualifyFromDate(sdf.parse(qualifyFromDateStr + "-01 00:00:00"));// 合同开始时间
		}
		if (qualifyEndDateStr != null && !qualifyEndDateStr.isEmpty()) {
			pro.setQualifyEndDate(sdf.parse(qualifyEndDateStr + "-01 00:00:00"));// 合同结束时间
		}
		// 投标单位授权代表社保缴纳时间
		String socialSecurityBeginTimeStr = request.getParameter("socialSecurityBeginTimeStr");// 社保开始时间
		String socialSecurityEndTimeStr = request.getParameter("socialSecurityEndTimeStr");// 社保结束时间
		if (socialSecurityBeginTimeStr != null && !socialSecurityBeginTimeStr.isEmpty()) {
			pro.setSocialSecurityBeginTime(sdf.parse(socialSecurityBeginTimeStr + "-01 00:00:00"));// 社保开始时间
		}
		if (socialSecurityEndTimeStr != null && !socialSecurityEndTimeStr.isEmpty()) {
			pro.setSocialSecurityEndTime(sdf.parse(socialSecurityEndTimeStr + "-01 00:00:00"));// 社保结束时间
		}
		// 采购机构网站
		DataSet dataset = dataSetService.get(DataSet.class, Constant.DATASET_ID);
		pro.setProcurementAddr(dataset.getProcurementAddr());
		pro.setProcurementUrl(dataset.getProcurementUrl());
		pro.setOthereRequire(project.getOthereRequire());
		pro.setPerContent(project.getPerContent());
		pro.setContractAmount(project.getContractAmount());
		pro.setBidType(project.getBidType());
		pro.setIsUnit(project.getIsUnit());
		pro.setCompileTime(new Date());// 编制时间
		pro.setResponseFile(project.getResponseFile());// 响应文件资料
		//pro.setManagerTel(project.getManagerTel());// 项目负责人电话
		// 工程类属性
		pro.setTimeLimit(project.getTimeLimit());// 工程工期
		pro.setQualityYears(project.getQualityYears());// 质保期
		pro.setCaluType(project.getCaluType());// 计价方式
		pro.setBiderLevelRequire(project.getBiderLevelRequire());// 竞标人资质等级要求
		pro.setBiderManagerRequire(project.getBiderManagerRequire());// 竞标人项目经理资质等级要求
		pro.setRecommendBrand(project.getRecommendBrand());// 推荐品牌
		pro.setRemind(project.getRemind());// 注意事项
		pro.setParentProjCode(project.getParentProjCode());// 上次开标项目
		pro.setAchievement(project.getAchievement());// 业绩
		pro.setIsAfterAudit(project.getIsAfterAudit());//是否资质后审
		pro.setAfterAuditDate(afterAuditDate);//资质后审时间
		
		// 项目关联清单附件信息
		if (budgetMenuData != null) {
			String budgetMenuStr[] = budgetMenuData.split(",");
			Resources res = null;
			for (String budgetMenuId : budgetMenuStr) {
				res = FileResUtil.getResources(budgetMenuId);
				if (res != null) {
					res.setBusinessId(pro.getId());
					this.projectInfoService.saveOrUpdate(res);// 更新
				}
			}
		}

		this.projectInfoService.saveOrUpdate(pro);
		
		// 生成world编制文档
		generateWord(request, pro);
		
		
		// 流程 完成任务
		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		//编制提交  设置超时审核时间
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("confirmTime", StringUtil.getISODate(project.getValidTime()));//编制审核确认截止时间
		variables.put("isAfterAudit", pro.getIsAfterAudit());//是否资质后审

		workflowProcessInstanceService.complete(task.getId(), variables);
 
		return Constant.SUCCESS;
	}
	
	
	/**
	 * @description 生成world方法
	 * @author wwang
	 * @date 2016-8-29
	 * @param request
	 * @param projectId
	 * @param project
	 */
	@SuppressWarnings("all")
	private void generateWord(HttpServletRequest request, ProjectInfo project) {
		// 数据处理
		project.setFundFromName(DictUtil.dict("fundFroms", project.getFundFrom()).getName());// 资金来源

		String oldName = project.getName() + "-竞价文件.doc";

		// 判断使用world模板版本
		String worldXmlPath = "nb-trade-goods.xml";// 模板名称
		// 项目类型
		if (Constant.PROJECTCATAGORY_GOODSID.equals(project.getCatagoryId())) {// 货物类
			worldXmlPath = "nb-trade-goods.xml";
		} else if (Constant.PROJECTCATAGORY_SERVICEID.equals(project.getCatagoryId())) {// 服务类
			worldXmlPath = "nb-trade-service.xml";
		} else if (Constant.PROJECTCATAGORY_ENGINEERINGID.equals(project.getCatagoryId())) {// 工程类
			worldXmlPath = "nb-trade-engineering.xml";
		} else if (Constant.PROJECTCATAGORY_PROPERTYID.equals(project.getCatagoryId())) {// 产权类
			// TODO 产权类的竞价文件模板
			worldXmlPath = "nb-trade-goods.xml";
		}

		// 得到文件的相对路径
		// 得到文件的相对路径
		String relativePath = File.separator + "project";
		String uploadPath = request.getSession().getServletContext().getRealPath("file_resource") + relativePath;
		File filePath = new File(uploadPath);
		// 判断文件夹是否存在，如果不存在给与创建出来
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		// 保存文档到res数据
		List<Resources> resList = FileResUtil.findResources(project.getId());
		// 删除之前的生成的竞价文件
		for (Resources resources : resList) {
			if (resources.getFunctionFlog() == 5) {
				FileResUtil.deleteFile(resources.getId(), request);
			}
		}
		Resources res = new Resources();
		String exeName = ".doc";
		res.setExeName(exeName);
		res.setFilePath(relativePath);
		res.setFileSize(50L);
		res.setOldName(oldName);
		res.setBusinessId(project.getId());
		res.setFunctionFlog(5);// 设置文件功能类型(竞价文件)
		FileResUtil.addFileRes(res); // 保存文件记录

		// 生成文档
		// world保存的真实路径
		String path = uploadPath + "/" + res.getId() + ".doc";
		Map map = new HashMap();
		// 时间
		map.put("maxDate", DateUtils.dataToUpper(new Date()));

		// 项目信息
		map.put("project", project);

		List<String> responseFile = new ArrayList<String>();
		Collections.addAll(responseFile, project.getResponseFile().replace("-@", "").split("@"));
		map.put("responseFile", responseFile);

		// 开标前30分钟
		map.put("bidStartTimeBefore", StringUtil.computeDate(project.getBidStartTime(), 0, 0, 0, 0, -30, 0));

		WordHandler world = new WordHandler();
		world.generateWord(path, map, worldXmlPath);// worldXmlPath
	}
	
	/**
	 * @description 生成world文档预览
	 * @author wwang
	 * @date 2016年9月21日
	 * @param request
	 * @param project
	 * @param bidStartDateStr
	 * @param bidStartTimeStr
	 * @param qualifyFromDateStr
	 * @param qualifyEndDateStr
	 * @param budgetMenuData
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/generateWord")
	@ResponseBody
	public String generateWord(HttpServletRequest request, ProjectInfo project,
			String bidStartDateStr,String bidStartTimeStr, 
			String qualifyFromDateStr, String qualifyEndDateStr,
			String afterAuditDateStr, String afterAuditTimeStr,
			String budgetMenuData)
			throws Exception {
		
		// 开标时间处理
		Date bidStartTime = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (bidStartDateStr != null && !bidStartDateStr.isEmpty()) {
			String bidStartStr = bidStartDateStr + " " + bidStartTimeStr + ":00:00";
			bidStartTime = StringUtil.StringToDate(bidStartStr);
		}
		
		// 资质后审时间处理
		Date afterAuditDate = null;
		if (afterAuditDateStr != null && !afterAuditDateStr.isEmpty()) {
			String afterAuditStr = afterAuditDateStr + " " + afterAuditTimeStr + ":00:00";
			afterAuditDate = StringUtil.StringToDate(afterAuditStr);
		}


		// 保存项目信息
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, project.getId());
		pro.setDeliveryPoint(project.getDeliveryPoint());
		pro.setDeliveryLimit(project.getDeliveryLimit());
		pro.setPromissMoney(project.getPromissMoney());
		pro.setManageRoom(project.getManageRoom());
		pro.setQualifyFromDate(project.getQualifyFromDate());
		pro.setQualifyEndDate(project.getQualifyEndDate());
		pro.setValidTime(project.getValidTime());
		pro.setBidStartTime(bidStartTime);
		// 投标单位授权代表社保缴纳时间
		String socialSecurityBeginTimeStr = request.getParameter("socialSecurityBeginTimeStr");// 社保开始时间
		String socialSecurityEndTimeStr = request.getParameter("socialSecurityEndTimeStr");// 社保结束时间
		if (socialSecurityBeginTimeStr != null && !socialSecurityBeginTimeStr.isEmpty()) {
			pro.setSocialSecurityBeginTime(sdf.parse(socialSecurityBeginTimeStr + "-01 00:00:00"));// 社保开始时间
		}
		if (socialSecurityEndTimeStr != null && !socialSecurityEndTimeStr.isEmpty()) {
			pro.setSocialSecurityEndTime(sdf.parse(socialSecurityEndTimeStr + "-01 00:00:00"));// 社保结束时间
		}
		// 采购机构网站
		DataSet dataset = dataSetService.get(DataSet.class, Constant.DATASET_ID);
		pro.setProcurementAddr(dataset.getProcurementAddr());
		pro.setProcurementUrl(dataset.getProcurementUrl());
		pro.setOthereRequire(project.getOthereRequire());
		pro.setPerContent(project.getPerContent());
		pro.setContractAmount(project.getContractAmount());
		pro.setNoteText(project.getNoteText());// 前注文本
		pro.setBidType(project.getBidType());
		pro.setIsUnit(project.getIsUnit());
		pro.setCompileTime(new Date());// 编制时间
		pro.setResponseFile(project.getResponseFile());// 响应文件资料
		// 工程类属性
		pro.setTimeLimit(project.getTimeLimit());// 工程工期
		pro.setQualityYears(project.getQualityYears());// 质保期
		pro.setCaluType(project.getCaluType());// 计价方式
		pro.setBiderLevelRequire(project.getBiderLevelRequire());// 竞标人资质等级要求
		pro.setBiderManagerRequire(project.getBiderManagerRequire());// 竞标人项目经理资质等级要求
		pro.setRecommendBrand(project.getRecommendBrand());// 推荐品牌
		pro.setRemind(project.getRemind());// 注意事项
		pro.setParentProjCode(project.getParentProjCode());// 上次开标项目
		pro.setAchievement(project.getAchievement());//业绩
		pro.setIsAfterAudit(project.getIsAfterAudit());//是否资质后审
		pro.setAfterAuditDate(afterAuditDate);//资质后审时间
		this.projectInfoService.saveOrUpdate(pro);

		// 生成world
		generateWord(request, pro);
		List<Resources> res = FileResUtil.findResources(project.getId());
		return JSONArray.fromObject(res).toString();
	}
	
	/**
	 * @description 项目编制保存
	 * @author wei
	 * @date 2016-8-15
	 * @param session
	 * @param project
	 * @param budgetMenuData
	 * @return
	 * @throws Exception
	 * @throws IOException
	 */
	@RequestMapping("/buyer/saveCompile")
	@ResponseBody
	public String saveCompile(HttpSession session, HttpServletRequest request, ProjectInfo project,
			String bidStartDateStr, String bidStartTimeStr,
			String qualifyFromDateStr, String qualifyEndDateStr,
			String afterAuditDateStr,String afterAuditTimeStr,
			String budgetMenuData) throws Exception {
		User user = (User) session.getAttribute("loginUser");
		
		// 开标时间处理
		Date bidStartTime = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (bidStartDateStr != null && !bidStartDateStr.isEmpty()&&bidStartTimeStr!=null&&!bidStartTimeStr.isEmpty()) {
			String bidStartStr = bidStartDateStr + " " + bidStartTimeStr + ":00:00";
			bidStartTime = StringUtil.StringToDate(bidStartStr);
		}
		
		// 资质后审时间处理
		Date afterAuditDate = null;
		if (afterAuditDateStr != null && !afterAuditDateStr.isEmpty()) {
			String afterAuditStr = afterAuditDateStr + " " + afterAuditTimeStr + ":00:00";
			afterAuditDate = StringUtil.StringToDate(afterAuditStr);
		}

		// 保存项目信息
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, project.getId());
		pro.setDeliveryPoint(project.getDeliveryPoint());
		pro.setDeliveryLimit(project.getDeliveryLimit());
		pro.setPromissMoney(project.getPromissMoney());
		pro.setManageRoom(project.getManageRoom());
		pro.setQualifyFromDate(project.getQualifyFromDate());
		pro.setQualifyEndDate(project.getQualifyEndDate());
		pro.setValidTime(project.getValidTime());
		pro.setBidStartTime(bidStartTime);

		// 投标单位授权代表社保缴纳时间
		String socialSecurityBeginTimeStr = request.getParameter("socialSecurityBeginTimeStr");// 社保开始时间
		String socialSecurityEndTimeStr = request.getParameter("socialSecurityEndTimeStr");// 社保结束时间
		if (socialSecurityBeginTimeStr != null && !socialSecurityBeginTimeStr.isEmpty()) {
			pro.setSocialSecurityBeginTime(sdf.parse(socialSecurityBeginTimeStr + "-01 00:00:00"));// 社保开始时间
		}
		if (socialSecurityEndTimeStr != null && !socialSecurityEndTimeStr.isEmpty()) {
			pro.setSocialSecurityEndTime(sdf.parse(socialSecurityEndTimeStr + "-01 00:00:00"));// 社保结束时间
		}

		// 采购机构网站
		DataSet dataset = dataSetService.get(DataSet.class, Constant.DATASET_ID);
		pro.setProcurementAddr(dataset.getProcurementAddr());
		pro.setProcurementUrl(dataset.getProcurementUrl());
		pro.setOthereRequire(project.getOthereRequire());
		pro.setPerContent(project.getPerContent());
		pro.setContractAmount(project.getContractAmount());
		pro.setNoteText(project.getNoteText());// 前注文本
		pro.setBidType(project.getBidType());
		pro.setIsUnit(project.getIsUnit());
		pro.setCompileTime(new Date());// 编制时间
		pro.setResponseFile(project.getResponseFile());// 响应文件资料
		pro.setManagerTel(project.getManagerTel());// 项目负责人电话
		// 工程类属性
		pro.setTimeLimit(project.getTimeLimit());// 工程工期
		pro.setQualityYears(project.getQualityYears());// 质保期
		pro.setCaluType(project.getCaluType());// 计价方式
		pro.setBiderLevelRequire(project.getBiderLevelRequire());// 竞标人资质等级要求
		pro.setBiderManagerRequire(project.getBiderManagerRequire());// 竞标人项目经理资质等级要求
		pro.setRecommendBrand(project.getRecommendBrand());// 推荐品牌
		pro.setRemind(project.getRemind());// 注意事项
		pro.setParentProjCode(project.getParentProjCode());// 上次开标项目
		pro.setAchievement(project.getAchievement());// 业绩
		pro.setIsAfterAudit(project.getIsAfterAudit());//是否资质后审
		pro.setAfterAuditDate(afterAuditDate);//资质后审时间
		
		// 项目关联清单附件信息
		if (budgetMenuData != null) {
			String budgetMenuStr[] = budgetMenuData.split(",");
			Resources res = null;
			for (String budgetMenuId : budgetMenuStr) {
				res = FileResUtil.getResources(budgetMenuId);
				if (res != null) {
					res.setBusinessId(pro.getId());
					this.projectInfoService.saveOrUpdate(res);// 更新
				}
			}
		}
		projectInfoService.saveOrUpdate(pro);
		return Constant.SUCCESS;

	}
	
	/**
	 * 编制审核页面
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/centerAuditor/auditInput")
	public ModelAndView auditInput(String projectId) {
		ModelAndView mv = new ModelAndView("/auction/center_auditor/audit-input");
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);
		mv.addObject("project", project);
		return mv;
	}
	
	/**
	 * @description 编制审核操作
	 * @return String
	 */
	@RequestMapping("/centerAuditor/approve")
	@ResponseBody
	public String approve(HttpSession session, ProjectInfo projectInfo,Integer compileAudit) {
		//当前时间已超过16:30,无法进行确认
		String nowStr = DateUtils.simpleDateFormat(new Date(), "yyyy-MM-dd");
		Date validateTime = DateUtils.simpleDateFormat(nowStr + " 16:30:00", "yyyy-MM-dd HH:mm:ss");
		if (new Date().getTime() >= validateTime.getTime()) {
			return "false";
		}
		
		User suser = (User) session.getAttribute("loginUser");
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectInfo.getId());
//		pro.setAuditId(suser.getId());
//		pro.setAuditName(suser.getName());
//		pro.setAuditTime(new Date());// 审核时间
//		//pro.setManageName(suser.getLoginName());//审核人名称
//		pro.setManagerTel(suser.getTel());//联系电话
		
		String reasonTemp="";
		if(compileAudit==COMPILEAUDITPASS){//通过
			reasonTemp=projectInfo.getCancelReason()+"</td><th>审核结果</th><td>审核通过";
			//生成项目编号
			pro.setCode(projectInfoService.generateProjectCode(pro));
			
			// 推送信息至银行（投标保证金）
			boolean result = postBank(pro);
			if (!result) {//投标保证金推送失败
				return "postbankfaill";
			}
		}else if(compileAudit==COMPILEAUDITNPASS){//不通过
			reasonTemp=projectInfo.getCancelReason()+"</td><th>审核结果</th><td>审核不通过";
		}else{//结束项目
			reasonTemp=projectInfo.getCancelReason()+"</td><th>审核结果</th><td>结束项目";
		}
		this.projectInfoService.saveOrUpdate(pro);

		// 流程 任务完成
		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("compileAudit", compileAudit);//审核结果
		variables.put("showTime", StringUtil.getISODate(pro.getBidStartTime()));//开标时间
		
		// 添加批注
		workflowProcessInstanceService.addComment(suser.getLoginName(), task.getId(), pro.getWorkflowId(),
				reasonTemp);

		workflowProcessInstanceService.complete(task.getId(), variables);
		return Constant.SAVE_SUCCESS;
	}
	
	/**
	 * 推送信息至银行操作（投标保证金）
	 *
	 * @return
	 */
	public boolean postBank(ProjectInfo pi) {

		// 第一次
		int n = 1;

		try {
			int _ret = depositService.regToBank(pi.getId());
			if (_ret == 1) {
				System.out.print("注册成功!");
				return true;
			} else {
				System.out.print("注册 不成功");
				n++;
			}
		} catch (IOException e) {
			System.out.print("注册 不成功，出现异常");
			e.printStackTrace();
			n++;
		}

		// 第二次
		try {
			int _ret = depositService.regToBank(pi.getId());
			if (_ret == 1) {
				System.out.print("第二次注册成功!");
				return true;
			} else {
				System.out.print("第二次注册 不成功");
				n++;
			}
		} catch (IOException e) {
			System.out.print("第二次注册 不成功，出现异常");
			e.printStackTrace();
			n++;
		}

		// 第三次
		try {
			int _ret = depositService.regToBank(pi.getId());
			if (_ret == 1) {
				System.out.print("第三次注册成功!");
				return true;
			} else {
				System.out.print("第三次注册 不成功");
				n++;
			}
		} catch (IOException e) {
			System.out.print("第三次注册 不成功，出现异常");
			e.printStackTrace();
			n++;
		}

		if (n >= 3) {
			// 发布三次未注册上的消息给系统管理 员
			//this.notifyService.savePostBankFallNotify(pi);
			return false;
		}
		return false;
	}
	
	/**
	 * 投标保存
	 * @param session
	 * @param projectBidInfo
	 * @param budgetMenuData
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/bidder/saveShot")
	@ResponseBody
	public String saveShot(HttpSession session, ProjectBidInfo projectBidInfo, String budgetMenuData) throws Exception {
		// 获取投标人信息
		User user = (User) session.getAttribute("loginUser");
		RegisterUser registerUser = this.projectInfoService.get(RegisterUser.class, user.getRegisterId());

		ProjectBidInfo projBid = this.projectInfoService.get(ProjectBidInfo.class, projectBidInfo.getId());
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectBidInfo.getProjectId());
		// 判断是否已经投过标了
		ProjectBidInfo pb = projectInfoService.getProjectBidderByProjIdAndBidderId(projectBidInfo.getProjectId(),
				registerUser.getId());
		if (pb != null) {
			projBid = pb;
		}
		// 校验
		// 2、保证金缴纳校验
		// 2.1 判断是否为该项目类型的注册账号
		String registerCategory = this.registerUserService.getDepositCategoryName(registerUser.getId());
		if (!registerCategory.contains(project.getCatagoryName())) {
			return Constant.NO_REG_QUALIFICA_BID;
		}

		// 2.2 判断是否缴纳协议保证金
		String depositCategory = this.registerUserService.getDepositCategory(registerUser.getId());
		if (!depositCategory.contains(project.getCatagoryId()) && project.getPromissMoney() != 0) {// 保证金为0，不需要缴纳
			// 2.3 判断是否缴纳单项保证金
			int ifPaySingleDeposit = depositService.ifPaySingleDeposit(registerUser.getId(), project.getId(),
					registerUser.getLoginName(), project.getName());
			if (ifPaySingleDeposit != 1 && project.getPromissMoney() != 0) {// 保证金为0，不需要缴纳//已交为1,未交为0,错误  为 -1
				if(ifPaySingleDeposit==5){//银行户名或开户行与系统帐户名或开户行不一致
					return Constant.ATYPISM;
				}
				return Constant.NO_QUALIFICA_BID;
			}
		}

		// 数据处理
		if (projBid == null) {
			projBid = new ProjectBidInfo();
		}
		projBid.setUserId(registerUser.getId());// 投标人id
		projBid.setBidderName(registerUser.getLoginName());// 单位名称
		projBid.setProjectId(projectBidInfo.getProjectId());// 项目id
		projBid.setProjectName(project.getName());// 项目名称
		projBid.setBidAmount(projectBidInfo.getBidAmount());// 报价总额
		Calendar cd = Calendar.getInstance();
		projBid.setBidTime(cd.getTime());// 投标时间
		projBid.setMillisecond(cd.get(Calendar.MILLISECOND));//投标时间毫米数
		projBid.setConsignor(projectBidInfo.getConsignor());// 委托人
		projBid.setConsignorIdCard(projectBidInfo.getConsignorIdCard());// 委托人身份证
		projBid.setConsignorPhone(projectBidInfo.getConsignorPhone());// 委托人联系方式
		projBid.setEvalutionResult(1);//不评标时默认有效标
		this.projectInfoService.save(projBid);

		// 项目关联清单附件信息
		if (budgetMenuData != null) {
			String budgetMenuStr[] = budgetMenuData.split(",");
			Resources res = null;
			for (String budgetMenuId : budgetMenuStr) {
				res = FileResUtil.getResources(budgetMenuId);
				if (res != null) {
					res.setBusinessId(projectBidInfo.getProjectId() + "," + registerUser.getId());// 项目id+用户Id
					this.projectInfoService.saveOrUpdate(res);// 更新
				}
			}
		}

		// ?、禁投校验提醒
		if (registerUser.getForbidStartDate() != null) {
			Date forbidStartDate = registerUser.getForbidStartDate();// 禁投开始日期
			Date forbidEndDate = registerUser.getForbidEndDate();// 禁投结束日期
			if (forbidStartDate != null && forbidEndDate != null && forbidEndDate.compareTo(new Date()) >= 0) {// 禁投结束日期大于当前日期
				return Constant.PROJECT_NO_BID_SAVE_UNSUCCESS;
			}
		}

		return Constant.SUCCESS;
	}
	
	/**
	 * 投标提交
	 * @param session
	 * @param projectBidInfo
	 * @param budgetMenuData
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/bidder/doSubmitShot")
	@ResponseBody
	public String doSubmitShot(HttpSession session, ProjectBidInfo projectBidInfo, String budgetMenuData)
			throws Exception {
		User user = (User) session.getAttribute("loginUser");
		RegisterUser registerUser = this.projectInfoService.get(RegisterUser.class, user.getRegisterId());

		ProjectBidInfo projBid =null;
		if(!"".equals(projectBidInfo.getId())){
			projBid=this.projectInfoService.get(ProjectBidInfo.class, projectBidInfo.getId());
		}
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectBidInfo.getProjectId());
		// 判断是否已经投过标了
		boolean isBid = projectInfoService.isBidByProjIdAndBidderId(project.getId(), registerUser.getId());
		if (isBid) {
			return Constant.EXIT_BID;
		}

		// 是否能提交投标结果判断
		// 开标前30分钟，才能提交
		Date openBIdBeforeTime = StringUtil.computeDate(project.getBidStartTime(), 0, 0, 0, 0, -30, 0);
		if (new Date().compareTo(project.getBidStartTime()) <= 0// 当前时间小于且等于开标时间
				&& new Date().compareTo(openBIdBeforeTime) >= 0// 当前时间大于等于开标前的30分钟
				&& project.getStatus() == Integer.valueOf(ProjectStatus.WAIT_SHOT.toString())) {// 项目状态为待开标
			if (projBid == null || projBid.getFlag() != 1) {// 投标结果未提交
				// 校验
				// 2、保证金缴纳校验
				// 2.1 判读是否为该项目类型的注册账号
				String registerCategory = this.registerUserService.getDepositCategoryName(registerUser.getId());
				if (!registerCategory.contains(project.getCatagoryName())) {
					return Constant.NO_REG_QUALIFICA_BID;
				}

				// 2.2 判断是否缴纳协议保证金
				String depositCategory = this.registerUserService.getDepositCategory(registerUser.getId());
				if (!depositCategory.contains(project.getCatagoryId()) && project.getPromissMoney() != 0) {// 保证金为0，不需要缴纳
					// 2.3 判断是否缴纳单项保证金
					int ifPaySingleDeposit = depositService.ifPaySingleDeposit(registerUser.getId(), project.getId(),
							registerUser.getLoginName(), project.getName());
					if (ifPaySingleDeposit != 1 && project.getPromissMoney() != 0) {// 保证金为0，不需要缴纳//已交为1,未交为0,错误 为 -1
						if(ifPaySingleDeposit==5){//银行户名或开户行与系统帐户名或开户行不一致
							return Constant.ATYPISM;
						}
						return Constant.NO_QUALIFICA_BID;
					}
				}


				// 数据处理
				if (projBid == null) {
					projBid = new ProjectBidInfo();
				}

				projBid.setUserId(registerUser.getId());// 投标人id
				projBid.setBidderName(registerUser.getLoginName());// 单位名称
				projBid.setProjectId(projectBidInfo.getProjectId());// 项目id
				projBid.setProjectName(project.getName());// 项目名称
				projBid.setBidAmount(projectBidInfo.getBidAmount());// 报价总额
				Calendar cd = Calendar.getInstance();
				projBid.setBidTime(cd.getTime());// 投标时间
				projBid.setMillisecond(cd.get(Calendar.MILLISECOND));//投标时间毫米数
				projBid.setFlag(1);// 标识为 已提交
				projBid.setConsignor(projectBidInfo.getConsignor());// 委托人
				projBid.setConsignorIdCard(projectBidInfo.getConsignorIdCard());// 委托人身份证
				projBid.setConsignorPhone(projectBidInfo.getConsignorPhone());// 委托人联系方式
				projBid.setEvalutionResult(1);//不评标时默认有效标
				// 报价大于项目预算时自动无效标处理
				if (projBid.getBidAmount() > project.getBudgetAmount()) {
					projBid.setEvalutionResult(2);// 无效标
					return "outBudgetAmount";
				}

				// 项目关联清单附件信息(撤销理原因附件)
				if (budgetMenuData != null) {
					String budgetMenuStr[] = budgetMenuData.split(",");
					Resources res = null;
					for (String budgetMenuId : budgetMenuStr) {
						res = FileResUtil.getResources(budgetMenuId);
						if (res != null) {
							res.setBusinessId(projectBidInfo.getProjectId() + "," + registerUser.getId());// 项目id+用户Id
							this.projectInfoService.saveOrUpdate(res);// 更新
						}
					}
				}

				// ?、禁投校验提醒
				if (registerUser.getForbidStartDate() != null) {
					Date forbidStartDate = registerUser.getForbidStartDate();// 禁投开始日期
					Date forbidEndDate = registerUser.getForbidEndDate();// 禁投结束日期
					if (forbidStartDate != null && forbidEndDate != null && forbidEndDate.compareTo(new Date()) >= 0) {// 禁投结束日期大于当前日期
						return Constant.PROJECT_NO_BID_SAVE_UNSUCCESS;
					}
				}

				this.projectInfoService.saveOrUpdate(projBid);
				System.err.println("当前时间在开标前30分钟之内,可进行投标提交操作!");
				return Constant.SUCCESS;
			}
		}

		return Constant.NO_BID_SUBMIT_UNSUCCESS;
	}
	
	
	/**
	 * 中标待选择页面
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/centerAuditor/choiceBidders")
	public ModelAndView choiceBidders(String projectId) {
		ModelAndView mv = new ModelAndView("/projNB/buyer/bidder-change-new");
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);
		List<Resources> resList = FileResUtil.findResources(project.getId());
		mv.addObject("resList", resList);
		mv.addObject("project", project);
		return mv;
	}
	
//	/**
//	 * 提交选择中标单位
//	 * @param projectId
//	 * @param choiceType
//	 * @return
//	 */
//	@RequestMapping("/buyer/doSubmitChoiceBidder")
//	@ResponseBody
//	public String doSubmitChoiceBidder(HttpSession session, String projectId,@RequestParam(value = "bidInfoIds[]") String[] bidInfoIds
//			,Integer choiceType,String changeReason,Boolean isFinishAfterAudit,String budgetMenuData){
//		User user = (User) session.getAttribute("loginUser");
//		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectId);
//		// 流程 任务完成
//		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
//		Map<String, Object> variables = new HashMap<String, Object>();
//		Integer flowBid=null;
//		//采购人选择中标单位
//		if(SYSTEMCHOICE.equals(choiceType)){//系统最低价
//			//将所有投标信息赋值为不是中标单位
//			ProjectBidInfo pbInfo=new ProjectBidInfo();
//			pbInfo.setProjectId(projectId);
//			List<ProjectBidInfo> bidList = this.projectInfoService.findProjectBidListByProjectId(null, pbInfo);
//			for (ProjectBidInfo pb : bidList) {
//				if(pb.getIsMultHit()){
//					pb.setIsMultHit(false);//为中标单位
//					this.projectBidService.saveOrUpdate(pb);
//				}
//			}
//
//			//获取最低价中标单位id
//			ProjectBidInfo hitBidInfo=this.projectInfoService.getTendeeByProjId(projectId);
//			hitBidInfo.setIsMultHit(true);//为中标单位
//			this.projectBidService.saveOrUpdate(hitBidInfo);
//			flowBid=Integer.valueOf(ProjectStatus.WAIT_WIN_SURE.toString());
//		}else if(BUYERCHOICE.equals(choiceType)){//采购人选择
//			//将所有投标信息赋值为不是中标单位
//			ProjectBidInfo pbInfo=new ProjectBidInfo();
//			pbInfo.setProjectId(projectId);
//			List<ProjectBidInfo> bidList = this.projectInfoService.findProjectBidListByProjectId(null, pbInfo);
//			for (ProjectBidInfo pb : bidList) {
//				if(pb.getIsMultHit()){
//					pb.setIsMultHit(false);//为中标单位
//					this.projectBidService.saveOrUpdate(pb);
//				}
//			}
//			for (String bidInfoId : bidInfoIds) {
//				ProjectBidInfo hitBidInfo = this.projectBidService.get(ProjectBidInfo.class, bidInfoId);
//				hitBidInfo.setIsMultHit(true);//为中标单位
//				this.projectBidService.saveOrUpdate(hitBidInfo);
//			}
//			flowBid=Integer.valueOf(ProjectStatus.WAIT_WIN_SURE.toString());
//		}else{//采购人选择流标
//			flowBid=Integer.valueOf(ProjectStatus.WAIT_FAIL_SURE.toString());
//		}
//
//		// 项目关联清单附件信息
//		if (budgetMenuData != null) {
//			String budgetMenuStr[] = budgetMenuData.split(",");
//			Resources res = null;
//			for (String budgetMenuId : budgetMenuStr) {
//				res = FileResUtil.getResources(budgetMenuId);
//				if (res != null) {
//					res.setBusinessId(pro.getId());
//					this.projectInfoService.saveOrUpdate(res);// 更新
//				}
//			}
//		}
//		pro.setCancelReason(changeReason);//临时保存选择中标人理由
//		this.projectInfoService.saveOrUpdate(pro);
//
//		//完成资质后审,不需要资质后审
//		if(isFinishAfterAudit==null||isFinishAfterAudit||!pro.getIsAfterAudit()){
//			variables.put("flowBid", flowBid);
//			// 添加批注
//			workflowProcessInstanceService.addComment(pro.getCreateId(), task.getId(), pro.getWorkflowId(),
//					"changebiders_buyer", changeReason);
//
//			workflowProcessInstanceService.complete(task.getId(), variables);
//		}
//		return Constant.SUCCESS;
//	}
//
	/**
	 * 中标确认审核页面
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/centerAuditor/hitConfirm")
	public ModelAndView hitConfirm(String projectId) {
		ModelAndView mv = new ModelAndView("/projNB/center-auditor/hitconfirm-input");
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);


		mv.addObject("project", project);
		return mv;
	}
	
	/**
	 * 提交中标确认审核
	 * @param projectId
	 * @param flowOrHitShow
	 * @param budgetMenuData
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/centerAuditor/doSubmitHitConfirm")
	@ResponseBody
	public String doSubmitHitConfirm(String projectId, Integer flowOrHitShow, String cancelReason, String budgetMenuData) throws Exception {

		// 项目信息
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectId);
		String chooseType=pro.getChooseType()+"";

		// 取出任务
		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		Map<String, Object> variables = new HashMap<String, Object>();
		//初始化变量
		variables.put("reEdit",false);
		variables.put("flow",false);
		variables.put("hit",false);

		variables.put("flowOrHitShow",flowOrHitShow);  //兼容以前的代码
		//兼容以前的代码设置choiceTime为不可用：数据设置为1000天以后
        Date d= new Date();
		d=StringUtil.addOneDayDate(d,1000);
		variables.put("choiceTime",StringUtil.getISODate(d));

        //不足三家
		Boolean ifNoEnoughBidder = (Boolean)runtimeService.getVariables(pro.getWorkflowId()).get("noEnoughBidderFlow");
		String isPass="";      //保留flowOrHitShow参数兼容之前版本，并设置变量isPass便于后面阅读

		if(flowOrHitShow==932){//“审核人"点击不同意 ，发回采购人重选
			variables.put("reEdit",true);
			isPass="no";
		}else{
			isPass="yes";
			if(chooseType==null || chooseType.equals(BUYER_FLOW_DOWN+"")
					|| (ifNoEnoughBidder!=null && ifNoEnoughBidder) ){
				variables.put("flow",true);
			}else{
				variables.put("hit",true);
			}
		}

		DataSet dataset = dataSetService.get(DataSet.class, Constant.DATASET_ID);

		//根据选择的类型，设置流程变量
		if(chooseType==null || chooseType.equals(BUYER_FLOW_DOWN+"") ||
				(ifNoEnoughBidder!=null && ifNoEnoughBidder) )
			{
			pro.setFlowShowStartTime(new Date());//流标公示开始时间
			// 流标公示期
			int publicity = dataset.getFlowPublicity();// 公示天数
			String publicityDate = DateUtils.computeWorkDayDateStr(holidaySetService, new Date(), publicity);// (工作日)公示时间
			pro.setFlowShowEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(publicityDate));// 流标公示结束时间
			variables.put("flowShowTime", StringUtil.getISODate(publicityDate));
		}

		//有中标人并且“审核人”同意
		if(isPass.equals("yes") &&
				(chooseType.equals(Constant.CHOOSE_TYPE_SYSTEMCHOICE+"")
						|| chooseType.equals(Constant.CHOOSE_TYPE_BUYERCHOICE+"")
						|| chooseType.equals(""+Constant.CHOOSE_TYPE_SYSTEM_CHOOSE_MIN)) ){
			// 推送信息至银行（履约保证金）
			boolean executeResult = postBankFromExecute(pro);
			if (!executeResult) {//履约保证金推送失败
				return "postbanexecutekfaill";
			}
			String publicityDate = DateUtils.computeWorkDayDateStr(holidaySetService, new Date(),
					dataset.getBuyerPublicity());// (工作日)公示时间
			pro.setHitShowStartTime(new Date());// 中标公示开始时间
			pro.setShowEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(publicityDate));// 中标公示结束时间

			//TODO 报表统计设置中标信息
			variables.put("resultShowTime", StringUtil.getISODate(pro.getShowEndTime()));
		}


//		if(Integer.valueOf(ProjectStatus.WAIT_WIN_CHOICE.toString()).equals(isPass)){//中标确认不通过，流标
//			pro.setFlowShowStartTime(new Date());//流标公示开始时间
//			// 流标公示期
//			int publicity = dataset.getFlowPublicity();// 公示天数
//			String publicityDate = DateUtils.computeWorkDayDateStr(holidaySetService, new Date(), publicity);// (工作日)公示时间
//			pro.setFlowShowEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(publicityDate));// 流标公示结束时间
//			variables.put("flowShowTime", StringUtil.getISODate(publicityDate));
//		}else{//中标确认通过
//			// 推送信息至银行（履约保证金）
//			boolean executeResult = postBankFromExecute(pro);
//			if (!executeResult) {//履约保证金推送失败
//				return "postbanexecutekfaill";
//			}
//			String publicityDate = DateUtils.computeWorkDayDateStr(holidaySetService, new Date(),
//					dataset.getBuyerPublicity());// (工作日)公示时间
//			pro.setHitShowStartTime(new Date());// 中标公示开始时间
//			pro.setShowEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(publicityDate));// 中标公示结束时间
//
//			//TODO 报表统计设置中标信息
//
//			variables.put("resultShowTime", StringUtil.getISODate(pro.getShowEndTime()));
//		}
//
//		//如果是中心管理员重新返回
//		if(isPass ==Integer.parseInt(ProjectStatus.WAIT_WIN_SURE.toString())){
//			variables.put("isAfterAudit",pro.getIsAfterAudit());
//		}

		//交易时间
		pro.setTradeTime(new Date());
		pro.setCancelReason(cancelReason);
		this.projectInfoService.saveOrUpdate(pro);
		
		// 添加批注
		workflowProcessInstanceService.addComment(pro.getCreateId(), task.getId(), pro.getWorkflowId(),
				"hitconfirm_buyer", cancelReason);
		
		workflowProcessInstanceService.complete(task.getId(), variables);
		return Constant.SUCCESS;
	}
	
	/**
	 * 提交流标确认
	 * @param projectId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/centerAuditor/doSubmitFlowConfirm")
	@ResponseBody
	public String doSubmitFlowConfirm(String projectId) throws Exception{
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectId);

		// 完成任务
//		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
//		Map<String, Object> variables = new HashMap<String, Object>();
//		variables.put("flowOrHitShow", Integer.valueOf(ProjectStatus.SHOWING_FLOW.toString()));//流标
		// 流标公示期
		DataSet dataset = dataSetService.get(DataSet.class, Constant.DATASET_ID);
		int publicity = dataset.getFlowPublicity();// 公示天数
		String publicityDate = DateUtils.computeWorkDayDateStr(holidaySetService, new Date(), publicity);// (工作日)公示时间
		pro.setFlowShowEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(publicityDate));// 流标公示结束时间
//		variables.put("flowShowTime", StringUtil.getISODate(publicityDate));
		pro.setFlowShowStartTime(new Date());//流标公示开始时间
		pro.setStatus(Integer.parseInt(ProjectStatus.FLOW_DOWN.toString()));		//交易时间
		pro.setTradeTime(new Date());
//		workflowProcessInstanceService.complete(task.getId(), variables);
		this.projectInfoService.saveOrUpdate(pro);

		//手动显示流标id
		String webId = (String) runtimeService.getVariable(pro.getWorkflowId(), "documentId");    //获得发文的id
		WebContent web = this.projectInfoService.get(WebContent.class, webId);

		this.generateFlowPublicity(pro,web,true);
		projectInfoService.saveOrUpdate(web);

		return Constant.SUCCESS;
	}


	private WebContent generateFlowPublicity(ProjectInfo pi,WebContent web,Boolean isDisplay){
		final String modelPath = IDepositService.class.getResource("/publicity").getPath();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		String tempContent=CommUtil.readStringFromFile(modelPath+"/"+"flowPublicity.html","utf-8");//模板文件目录
		Map map = new HashMap();
		map.put("flowReason", pi.getCancelReason());
		map.put("project", pi);
		map.put("flowTime", sdf.format(new Date()));
		//公示附件
		String pubResName = "";
		List<Resources> resList = FileResUtil.findResources(pi.getId());
		for (Resources resource : resList) {
			if (resource.getFunctionFlog() == 27) {// 公示附件
				pubResName += "<a href='../web/fileView?resId=" + resource.getId() + "'>" + resource.getOldName()
						+ "</a> ";
			}
		}
		map.put("pubResName", pubResName);

		//生成内容
		String content = CommUtil.freemarkerProcess(map,tempContent);

		// 插入新闻数据
		if(web==null){
			web=new WebContent();
		}
		web.setTitle("【"+pi.getCatagoryName()+"】" + pi.getName() + "流标公告");
		web.setContent(content);
		web.setCreaterId(ActivitiMap.SUPERADMIN_ID);
		web.setCreateTime(new Date());
		web.setCreaterName("系统");
		web.setDeptId("1");
		web.setProjectId(pi.getId());
		web.setType("33");
		if (isDisplay) {
			web.setIsDisplay(0);//显示

			// 流标公示结束时间
			Date flowShowEndTime=getFlowShowEndTime();
			web.setEndShowTime(pi.getFlowShowEndTime());// 设置展示结束时间
		}else{
			web.setIsDisplay(1);//不显示
		}
		return web;
	}

	@Autowired
	private IHolidaySetService holidaySetServiceImpl;

	/**
	 * 获取流标公示结束时间
	 * @return
	 */
	private Date getFlowShowEndTime() {
		Date flowShowEndTime=new Date();
		// 流标公示期变量
		DataSet dataset = dataSetService.get(DataSet.class, Constant.DATASET_ID);
		int publicity = dataset.getFlowPublicity();// 公示天数
		String publicityDate = DateUtils.computeWorkDayDateStr(holidaySetServiceImpl, new Date(), publicity);// (工作日)公示时间
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			flowShowEndTime=format.parse(publicityDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return flowShowEndTime;
	}


	
	/**
	 * @description 发放中标通知书
	 * @author wwang
	 * @date 2016-8-24
	 * @param id
	 * @return
	 */
	@RequestMapping("/centerAuditor/noticBidInfo")
	@ResponseBody
	public String noticBidInfo(String id) {
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, id);
		pro.setReleaseAlertDoc(new Date());
		this.projectInfoService.saveOrUpdate(pro);

		// 流程 完成任务
		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		Map<String, Object> variables = new HashMap<String, Object>();
		List<String> rec = new ArrayList<String>();
		//获取中标单位
		List<ProjectBidInfo> bidInfos = this.projectInfoService.getProjectBiddersByProjId(id);
		for (ProjectBidInfo bidInfo : bidInfos) {
			rec.add(bidInfo.getId());// 中标人
		}
		rec.add(pro.getCreateId());// 采购方
		variables.put("receivers", rec);
		workflowProcessInstanceService.complete(task.getId(), variables);

		return Constant.SUCCESS;
	}
	
	/**
	 * 推送信息至银行操作（履约保证金）
	 *
	 * @return
	 */
	public boolean postBankFromExecute(ProjectInfo pi) {

		// 第一次
		int n = 1;

		try {
			int _ret = depositExecuteService.regToBank(pi.getId());
			if (_ret == 1) {
				System.out.print("注册成功!");
				return true;
			} else {
				System.out.print("注册 不成功");
				n++;
			}
		} catch (IOException e) {
			System.out.print("注册 不成功，出现异常");
			e.printStackTrace();
			n++;
		}

		// 第二次
		try {
			int _ret = depositExecuteService.regToBank(pi.getId());
			if (_ret == 1) {
				System.out.print("第二次注册成功!");
				return true;
			} else {
				System.out.print("第二次注册 不成功");
				n++;
			}
		} catch (IOException e) {
			System.out.print("第二次注册 不成功，出现异常");
			e.printStackTrace();
			n++;
		}

		// 第三次
		try {
			int _ret = depositExecuteService.regToBank(pi.getId());
			if (_ret == 1) {
				System.out.print("第三次注册成功!");
				return true;
			} else {
				System.out.print("第三次注册 不成功");
				n++;
			}
		} catch (IOException e) {
			System.out.print("第三次注册 不成功，出现异常");
			e.printStackTrace();
			n++;
		}

		if (n >= 3) {
			// 发布三次未注册上的消息给系统管理 员
			//this.notifyService.savePostBankFallNotify(pi);
			return false;
		}
		return false;
	}
	
	
	/**
	 * 校验中标人履约保证金是否缴纳
	 * 
	 * @return
	 */
	@RequestMapping("/buyer/validBidBond")
	@ResponseBody
	public String validBidBond(ProjectInfo project) {
		project = projectInfoService.get(ProjectInfo.class, project.getId());
		//查询银行接口，履约保证金缴纳信息
		List<Bank> bidBondInfoList = depositExecuteService.getDepositList(project.getId());
		List<ProjectBidInfo> bidInfos = this.projectInfoService.getProjectBiddersByProjId(project.getId());
		String noBidBondName = getNoBidBondName(bidBondInfoList, bidInfos);
		if("".equals(noBidBondName)){
			noBidBondName="ok";
		}
		return noBidBondName;
	}
	
	/**
	 * 获取没有缴纳履约保证金的中标单位
	 * @param bidBondInfoList
	 * @param bidInfos
	 * @return
	 */
	private String getNoBidBondName(List<Bank> bidBondInfoList,List<ProjectBidInfo> bidInfos ){
//		StringBuffer noBondName=new StringBuffer("");//没有缴纳保证的单位名称
//		List<String> banks=new ArrayList<>();
//		List<String> bankInAccts=new ArrayList<>();
//		//保证金户名
//		for (Bank bank : bidBondInfoList) {
//			if(bank!=null&&!"".equals(bank.getInName())){
//				banks.add(bank.getInName());
//			}
//		}da
//		//保证金银行卡号
//		for (Bank bank : bidBondInfoList) {
//			if(bank!=null&&!"".equals(bank.getInAcct())){
//				bankInAccts.add(bank.getInAcct());
//			}
//		}
//		for (ProjectBidInfo bidInfo : bidInfos) {
//			RegisterUser register = this.projectInfoService.get(RegisterUser.class, bidInfo.getUserId());
//			if(!banks.contains(bidInfo.getBidderName())
//					||!bankInAccts.contains(register.getAccount())){//没有缴纳保证金
//				noBondName.append("『"+bidInfo.getBidderName()+"』");
//			}
//		}
		
		//查询缴纳过的中标单位
		List<String> payBidderId=new ArrayList<>();//已经缴纳过的中标单位中标信息id
		for (ProjectBidInfo bidInfo : bidInfos) {
			RegisterUser register = this.projectInfoService.get(RegisterUser.class, bidInfo.getUserId());
			for (Bank bank : bidBondInfoList) {
				if(bidInfo.getBidderName().equals(bank.getInName())
						&&bank.getInAcct().equals(register.getAccount())){
					payBidderId.add(bidInfo.getId());
				}
			}
		}
		
		//获取没有缴纳保证的单位名称
		StringBuffer noBondName=new StringBuffer("");//没有缴纳保证的单位名称
		for (ProjectBidInfo bidInfo : bidInfos) {
			if(!payBidderId.contains(bidInfo.getId())){//没有缴纳保证金
				noBondName.append("『"+bidInfo.getBidderName()+"』");
			}
		}
		return noBondName.toString();
	}
	
	
	/**
	 * 上传合同
	 * 
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/buyer/doSubmitContract")
	@ResponseBody
	public String doSubmitContract(HttpSession session, HttpServletRequest request, String projectId,
			String budgetMenuData) {
		User user = (User) session.getAttribute("loginUser");

		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectId);
		// 上传人信息
		pro.setContactUpTime(new Date());
		pro.setContactUpUserId(user.getId());
		pro.setContactUpUserName(user.getLoginName());
		// 保存文档到res数据
		List<Resources> resList = FileResUtil.findResources(pro.getId());
		// 删除之前的生成的合同文件
		for (Resources resources : resList) {
			if (resources.getFunctionFlog() == 7) {// 合同
				FileResUtil.deleteFile(resources.getId(), request);
			}
		}
        //未上传合同
        if(budgetMenuData==null&&"".equals(budgetMenuData)){
            return "nocontract";
        }
		// 项目关联清单附件信息
		if (budgetMenuData != null) {
			String budgetMenuStr[] = budgetMenuData.split(",");
			Resources res = null;
			for (String budgetMenuId : budgetMenuStr) {
				res = FileResUtil.getResources(budgetMenuId);
				if (res != null) {
					res.setBusinessId(pro.getId());
					this.projectInfoService.saveOrUpdate(res);// 更新
				}
			}
		}
		projectInfoService.saveOrUpdate(pro);

		// 流程 完成任务
		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		workflowProcessInstanceService.complete(task.getId(), null);

		return Constant.SUCCESS;
	}
	
	/**
	 * 合同审核页面
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/centerAuditor/contractAuditInput")
	public ModelAndView contractAudit(String projectId) {
		ModelAndView mv = new ModelAndView("/projNB/center-auditor/contractaudit-input");
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);
		mv.addObject("project", project);
		return mv;
	}
	
	/**
	 * 项目合同审核操作
	 * 
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/centerAuditor/contractAudit")
	@ResponseBody
	public String contractAudit(HttpSession session, String projectId, String reason, Integer contactPass,
			String budgetMenuData) throws Exception {
		User user = (User) session.getAttribute("loginUser");
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectId);

		// 流程 完成任务
		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		Map<String, Object> variables = new HashMap<String, Object>();
		if (Integer.valueOf(ProjectStatus.CONTACT_AUDIT_NOT_PASS.toString()).equals(contactPass)) {// 不通过
			// 保存审核意见
			workflowProcessInstanceService.addComment(user.getId(), task.getId(), pro.getWorkflowId(), "contract_audit",
					reason+"</td><th>审核结果</th><td>审核不通过");
		} else {// 通过
			// 设置合同公示时间
			// 获取时间
			DataSet dataset = dataSetService.get(DataSet.class, Constant.DATASET_ID);
			int publicity = dataset.getPublicity();// 公示天数
			String publicityDate = DateUtils.computeWorkDayDateStr(holidaySetService, new Date(), publicity);// (工作日)公示时间
			variables.put("timeContact", StringUtil.getISODate(publicityDate));

			// 保存合同开始时间，结束时间
			pro.setContactBeginTime(new Date());
			pro.setContactEndTime(StringUtil.StringToDate(publicityDate));
			
			// 保存审核意见
			workflowProcessInstanceService.addComment(user.getId(), task.getId(), pro.getWorkflowId(), "contract_audit",
					reason+"</td><th>审核结果</th><td>审核通过");
		}
		variables.put("contactPass", contactPass);

		this.projectInfoService.saveOrUpdate(pro);

		workflowProcessInstanceService.complete(task.getId(), variables);

		return Constant.SUCCESS;
	}
	
	/**
	 * @description 上传验收报
	 * @author shy
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/buyer/uploadReceivingReport")
	@ResponseBody
	public String uploadReceivingReport(HttpSession session, HttpServletRequest request, String projectId,
			String budgetMenuData) {
		User user = (User) session.getAttribute("loginUser");
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectId);
		// 上传人信息
		pro.setAuditReportUpTime(new Date());
		pro.setAuditReportUpUserId(user.getId());
		pro.setAuditReportUpUserName(user.getLoginName());
		// 保存文档到res数据
		List<Resources> resList = FileResUtil.findResources(pro.getId());
		// 删除之前的生成的验收报告
		for (Resources resources : resList) {
			if (resources.getFunctionFlog() == 20) {// 验收报告
				FileResUtil.deleteFile(resources.getId(), request);
			}
		}
		// 项目关联清单附件信息
		if (budgetMenuData != null) {
			String budgetMenuStr[] = budgetMenuData.split(",");
			Resources res = null;
			for (String budgetMenuId : budgetMenuStr) {
				res = FileResUtil.getResources(budgetMenuId);
				if (res != null) {
					res.setBusinessId(pro.getId());
					res.setFunctionFlog(20);
					this.projectInfoService.saveOrUpdate(res);// 更新
				}
			}
		}
		this.projectInfoService.saveOrUpdate(pro);
		// 完成任务
		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		workflowProcessInstanceService.complete(task.getId(), null);

		return Constant.SUCCESS;
	}
	
	
	/**
	 * 验收报告审核页面
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/centerAuditor/receivingReportAuditInput")
	public ModelAndView receivingReportAuditInput(String projectId) {
		ModelAndView mv = new ModelAndView("/projNB/center-auditor/receivingreportaudit-input");
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);
		mv.addObject("project", project);
		return mv;
	}
	
	/**
	 * 验收报告审核操作
	 * 
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/centerAuditor/receivingReportAudit")
	@ResponseBody
	public String receivingReportAudit(HttpSession session, String projectId, String reason, Integer receiverPass,
			String budgetMenuData) throws Exception {
		User user = (User) session.getAttribute("loginUser");
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectId);

		// 流程 完成任务
		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		Map<String, Object> variables = new HashMap<String, Object>();
		if (Integer.valueOf(ProjectStatus.RECEIVING_UNAUTH.toString()).equals(receiverPass)) {// 不通过
			// 保存审核意见
			workflowProcessInstanceService.addComment(user.getId(), task.getId(), pro.getWorkflowId(), "receivingReson",
					reason+"</td><th>审核结果</th><td>审核不通过");
		} else {// 通过
			// 设置公示时间
			DataSet dataset = dataSetService.get(DataSet.class, Constant.DATASET_ID);
			int publicity = dataset.getReceivingPublicity();// 公示天数
			String publicityDate = DateUtils.computeWorkDayDateStr(holidaySetService, new Date(), publicity);// (工作日)公示时间
			variables.put("showReceiverTime", StringUtil.getISODate(publicityDate));
			
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			pro.setReceivingStratTime(new Date());
			pro.setReceivingEndTime(format.parse(publicityDate));
			
			// 保存审核意见
			workflowProcessInstanceService.addComment(user.getId(), task.getId(), pro.getWorkflowId(), "receivingReson",
					reason+"</td><th>审核结果</th><td>审核通过");
		}
		variables.put("receiverPass", receiverPass);

		this.projectInfoService.saveOrUpdate(pro);

		workflowProcessInstanceService.complete(task.getId(), variables);

		return Constant.SUCCESS;
	}
	
	
	/**
	 * @description 结项操作
	 * @author wwang
	 * @date 2016-8-24
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/centerAuditor/endProject")
	@ResponseBody
	public String endProject(String projectId) {
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectId);
		pro.setEndTime(new Date());
		// 项目跨度
		int allDays = DateUtils.daysBetween(pro.getCreateTime(), pro.getEndTime());
		pro.setAllDays(allDays);
		this.projectInfoService.saveOrUpdate(pro);

		// 流程 完成任务
		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		workflowProcessInstanceService.complete(task.getId(), null);

		return Constant.SUCCESS;
	}
	
	
	/**
	 * 验收报告打印
	 * 
	 * @param projectId
	 * @returnprintWinbidAlertt
	 */
	@RequestMapping("/printReceivinReport")
	public ModelAndView printReceivinReport(HttpSession session, String projectId,Boolean isShow,String bidId) {
		User user = (User) session.getAttribute("loginUser");
		//判断是否为投标用户
		ModelAndView mv = new ModelAndView("/projNB/public/project-receivin-report");
		ProjectInfo project = projectInfoService.get(ProjectInfo.class, projectId);
		if (isShow) {//显示打印页面
			RegisterUser registerUser = this.projectInfoService.get(RegisterUser.class, user.getRegisterId());
			ProjectBidInfo bidInfo = null;
			if(registerUser!=null){//中标人打印
				bidInfo = this.projectInfoService.getProjectBidderByProjIdAndBidderId(projectId,
						registerUser.getId());
			}else{//采购人打印
				bidInfo = this.projectInfoService.get(ProjectBidInfo.class, bidId);
			}
			
			mv.addObject("bidInfo", bidInfo);
		}else{//显示验收报告列表页面
			mv.setViewName("/projNB/public/receivin-report-list");
			//获取中标单位集合
			List<ProjectBidInfo> bidInfos = this.projectInfoService.getProjectBiddersByProjId(projectId);
			mv.addObject("bidInfos", bidInfos);
		}
		
		mv.addObject("project", project);
		
		
		return mv;
	}
	
	
	/**
	 *中标通知书列表页面
	 * 
	 * @param projectId
	 * @return 
	 */
	@RequestMapping("/printWinbidAlert")
	public ModelAndView printWinbidAlertt(HttpSession session, String projectId,Boolean isShow,String bidId) {
		User user = (User) session.getAttribute("loginUser");
		//判断是否为投标用户
		ModelAndView mv = new ModelAndView("/projNB/public/winbid-alert-print");
		ProjectInfo project = projectInfoService.get(ProjectInfo.class, projectId);
		if (isShow) {//显示打印页面
			RegisterUser registerUser = this.projectInfoService.get(RegisterUser.class, user.getRegisterId());
			ProjectBidInfo bidInfo = null;
			if(registerUser!=null){//中标人打印
				bidInfo = this.projectInfoService.getProjectBidderByProjIdAndBidderId(projectId,
						registerUser.getId());
			}else{//采购人打印
				bidInfo = this.projectInfoService.get(ProjectBidInfo.class, bidId);
			}
			
			mv.addObject("pb", bidInfo);
		}else{//显示中标通知书列表页面
			mv.setViewName("/projNB/public/winbid-alert-print-list");
			//获取中标单位集合
			List<ProjectBidInfo> bidInfos = this.projectInfoService.getProjectBiddersByProjId(projectId);
			mv.addObject("bidInfos", bidInfos);
		}
		
		mv.addObject("project", project);
		
		
		return mv;
	}

	/**
	 * @description 通过项目Id进行分配操作
	 * @return String
	 */
	@RequestMapping("/assign/projectAssign")
	@ResponseBody
	public String projectAssign(HttpSession session, ProjectInfo projectInfo) {

		User suser = (User) session.getAttribute("loginUser");
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectInfo.getId());
		pro.setAssignTime(new Date());
		pro.setAssignId(suser.getId());
		pro.setAssignName(suser.getName());

		User manager = userService.get(User.class, projectInfo.getAuditId());
		pro.setAuditId(projectInfo.getAuditId());
		pro.setAuditName(manager.getLoginName());
		pro.setAuditTime(new Date());// 审核时间
		pro.setManagerTel(manager.getTel());//联系电话
		this.projectInfoService.saveOrUpdate(pro);

		// 任务完成（项目分配）
		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("centerAuditor", projectInfo.getAuditId());
		workflowProcessInstanceService.complete(task.getId(), variables);
        LogUtil.addLog(new LogInfo("不评标项目["+pro.getName()+"]分配： "+projectInfo.getAuditId()+": "+task.getName(),
                suser.getId(), suser.getName(), String.valueOf(LogType.ADD.ordinal()), this.getClass().getSimpleName(), "1"));
		return Constant.SAVE_SUCCESS;
	}

	/**
	 * 评审纪要
	 * @param session
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/print/reviewRecord")
	public ModelAndView printReviewRecord(HttpSession session, String projectId) {
		ModelAndView mv = new ModelAndView("/proj/reviewFile/ReviewRecordNoBid");
		ProjectInfo pi = this.projectInfoService.get(ProjectInfo.class, projectId);// 项目信息
		Date bidStartTime = pi.getBidStartTime();
		//获取中标单位信息（非评标，多个中标单位）
		List<ProjectBidInfo> bidInfos = this.projectInfoService.getProjectBiddersByProjId(pi.getId());


		List<ProjectBidInfo> list = this.projectBidService.getProjectBidCount(projectId);
		// 有效标数量
		int effectiveCount = this.projectBidService.getProjectBidCountByProjIdAndEvalutionResult(projectId, Constant.EFFECTIVE);
		//获取最低价中标单位id
		ProjectBidInfo hitBidInfo=this.projectInfoService.getTendeeByProjId(projectId);

		mv.addObject("project", pi);
		mv.addObject("bidcount", list.size());
		mv.addObject("time", bidStartTime);
		mv.addObject("effectiveCount", effectiveCount);
		mv.addObject("bidders",bidInfos);
		mv.addObject("minimumPriceInfo",hitBidInfo);
		return mv;
	}

	/**
	 * 提交选择中标单位
	 * @param projectId
	 * @param choiceType
	 * @return
	 */
	@RequestMapping("/buyer/doSubmitChoiceBidder")
	@ResponseBody
	public String doSubmitChoiceBidder(HttpSession session, String projectId,@RequestParam(value = "bidInfoIds[]") String[] bidInfoIds
			,Integer choiceType,String changeReason){
		User user = (User) session.getAttribute("loginUser");
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectId);
		// 流程 任务完成
		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		Map<String, Object> variables = new HashMap<String, Object>();
		Integer flowBid=null;
		//采购人选择中标单位
		if(SYSTEMCHOICE.equals(choiceType)){//采购人选择系统最低价
			//将所有投标信息赋值为不是中标单位
			ProjectBidInfo pbInfo=new ProjectBidInfo();
			pbInfo.setProjectId(projectId);
			List<ProjectBidInfo> bidList = this.projectInfoService.findProjectBidListByProjectId(null, pbInfo);
			for (ProjectBidInfo pb : bidList) {
				if(pb.getIsMultHit()){
					pb.setIsMultHit(false);//为中标单位
					this.projectBidService.saveOrUpdate(pb);
				}
			}

			pro.setChooseType(choiceType);
			//获取最低价中标单位id
			ProjectBidInfo hitBidInfo=this.projectInfoService.getTendeeByProjId(projectId);
			hitBidInfo.setIsMultHit(true);//为中标单位
			this.projectBidService.saveOrUpdate(hitBidInfo);
			flowBid=Integer.valueOf(ProjectStatus.WAIT_WIN_SURE.toString());
		}else if(BUYERCHOICE.equals(choiceType)){//采购人选择
			//将所有投标信息赋值为不是中标单位
			ProjectBidInfo pbInfo=new ProjectBidInfo();
			pbInfo.setProjectId(projectId);
			List<ProjectBidInfo> bidList = this.projectInfoService.findProjectBidListByProjectId(null, pbInfo);
			for (ProjectBidInfo pb : bidList) {
				if(pb.getIsMultHit()){
					pb.setIsMultHit(false);//为中标单位
					this.projectBidService.saveOrUpdate(pb);
				}
			}
			for (String bidInfoId : bidInfoIds) {
				ProjectBidInfo hitBidInfo = this.projectBidService.get(ProjectBidInfo.class, bidInfoId);
				hitBidInfo.setIsMultHit(true);//为中标单位
				this.projectBidService.saveOrUpdate(hitBidInfo);
			}
			pro.setChooseType(choiceType);
			flowBid=Integer.valueOf(ProjectStatus.WAIT_WIN_SURE.toString());
		}else{//采购人选择流标
			//将所有投标信息赋值为不是中标单位
			ProjectBidInfo pbInfo=new ProjectBidInfo();
			pbInfo.setProjectId(projectId);
			List<ProjectBidInfo> bidList = this.projectInfoService.findProjectBidListByProjectId(null, pbInfo);
			for (ProjectBidInfo pb : bidList) {
				if(pb.getIsMultHit()){
					pb.setIsMultHit(false);//为中标单位
					this.projectBidService.saveOrUpdate(pb);
				}
			}
			flowBid=Integer.valueOf(ProjectStatus.WAIT_FAIL_SURE.toString());
			pro.setChooseType(choiceType);
		}


		pro.setCancelReason(changeReason);//临时保存选择中标人理由
		this.projectInfoService.saveOrUpdate(pro);
		variables.put("flowBid", flowBid);
		taskService.setVariables(task.getId(),variables);
		workflowProcessInstanceService.addComment(pro.getCreateId(), task.getId(), pro.getWorkflowId(), "changebiders_buyer", changeReason);
		return Constant.SUCCESS;
	}

	/**
	 * 中标人完成中标选择
	 * @return
	 */
	@RequestMapping("/buyer/afterChooseBidder")
	@ResponseBody
	public String afterChooseBidder(HttpSession session, String projectId,String budgetMenuData,Boolean isFinishAfterAudit) {
		User user = (User) session.getAttribute("loginUser");
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectId);
		if(pro.getChooseType()==null){//没有选择中标结果
			return "noChoose";
		}
		//资源保存
		if (budgetMenuData != null) {
			String budgetMenuStr[] = budgetMenuData.split(",");
			Resources res = null;
			for (String budgetMenuId : budgetMenuStr) {
				res = FileResUtil.getResources(budgetMenuId);
				if (res != null) {
					res.setBusinessId(projectId);
					this.projectInfoService.saveOrUpdate(res);// 更新
				}
			}
		}
	//完成资质后审,不需要资质后审
		boolean reviewRecord=false;
		//boolean  otherFile=false;
		if(isFinishAfterAudit==null||isFinishAfterAudit||!pro.getIsAfterAudit()){
			List<Resources> resList = FileResUtil.findResources(pro.getId());
			for(Resources resource:resList ){
                         if(resource.getFunctionFlog()==27){  //评审纪要
							 reviewRecord=true;
						 }
//						 if(resource.getFunctionFlog()==28){ //其他资料
//							 otherFile=true;
//						 }
			}
			if(reviewRecord){
				Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
				workflowProcessInstanceService.complete(task.getId(), null);
				return  Constant.SUCCESS;
			}else {
				return "supplementFile";
			}
		}else{
		//	Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		//	workflowProcessInstanceService.complete(task.getId(), null);
			return  Constant.SUCCESS;
		}

	}

    /**
     * 流标上传附件页面
     * @param projectId
     * @return
     */
	@RequestMapping("/uploadFlowFile")
    public ModelAndView updateFile(String projectId){
		ModelAndView mv = new ModelAndView("/projNB/buyer/flow-supplement-File");
		// 项目信息
		ProjectInfo project = projectInfoService.get(ProjectInfo.class, projectId);
		mv.addObject("project", project);
		// 附件
		if (!StringUtil.isEmpty(projectId)) {
			List<Resources> resList = FileResUtil.findResources(projectId);
			mv.addObject("resList", resList);
		}
		return mv;
    }

    /**
     *结束上传流标附件
     * @return
     */
    @RequestMapping("buyer/afterFlowDownUpFile")
    @ResponseBody
    public String  afterFlowDownUpFile(String projectId,String budgetMenuData){
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectId);
        //资源保存
        if (budgetMenuData != null) {
            String budgetMenuStr[] = budgetMenuData.split(",");
            Resources res = null;
            for (String budgetMenuId : budgetMenuStr) {
                res = FileResUtil.getResources(budgetMenuId);
                if (res != null) {
                    res.setBusinessId(projectId);
                    this.projectInfoService.saveOrUpdate(res);// 更新
                }
            }
        }

		boolean reviewRecord=false;
			List<Resources> resList = FileResUtil.findResources(pro.getId());
			for(Resources resource:resList ){
				if(resource.getFunctionFlog()==27){  //评审纪要
					reviewRecord=true;
				}
			}
      //流程
		if( reviewRecord){
			Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
			workflowProcessInstanceService.complete(task.getId(), null);
			return Constant.SUCCESS;
		}else {
			return "supplementFile";
		}
    }
	
	/**
	 * @description 评标补录资料 页面
	 * @author shy
	 * @date 2017年6月7日
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/supplementFile")
	@ResponseBody
	public ModelAndView supplementFile(String projectId) {
		ModelAndView mv = new ModelAndView("/projNB/center-auditor/supplement-File-input");
		// 项目信息
		ProjectInfo project = projectInfoService.get(ProjectInfo.class, projectId);
		mv.addObject("project", project);
		// 附件
		if (!StringUtil.isEmpty(projectId)) {
			List<Resources> resList = FileResUtil.findResources(projectId);
			mv.addObject("resList", resList);
		}
		return mv;
	}
	
	/**
	 * @description 提交评标补录资料
	 * @author shy
	 * @date 2017年6月29日
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/doSupplementFile")
	@ResponseBody
	public String doSupplementFile(ProjectInfo project, Integer showEndDay, String budgetMenuData) throws Exception {
		// 项目信息
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, project.getId());
		// 保存补录的 项目关联清单附件信息
		if (budgetMenuData != null) {
			String budgetMenuStr[] = budgetMenuData.split(",");
			Resources res = null;
			for (String budgetMenuId : budgetMenuStr) {
				res = FileResUtil.getResources(budgetMenuId);
				if (res != null) {
					res.setBusinessId(pro.getId());
					this.projectInfoService.saveOrUpdate(res);// 更新
				}
			}
		}
		this.projectInfoService.saveOrUpdate(pro);
		return Constant.SUCCESS;
	}


	/**
	 * @description
	 * @author shy 打开归档资料选择页面
	 * @date 2017-6-29
	 * @param projectId
	 */
	@RequestMapping("/leader/pigeonholeInput")
	@ResponseBody
	public ModelAndView pigeonholeInput(String projectId, HttpSession session) {
		User user = (User) session.getAttribute("loginUser");
		UserRole userRole = roleService.findUserRole(ActivitiMap.BUYER_ID, user.getId());// 是否为采购人
		UserRole centerAuditor = roleService.findUserRole(ActivitiMap.CENTERAUDITOR_ID, user.getId());// 是否为中心审核人
		UserRole bizmanageRole = roleService.findUserRole(ActivitiMap.BIZMANAGER_ID, user.getId());// 是否为业务管理员

		ModelAndView mv = new ModelAndView("/projNB/center-auditor/file-pigeonhole-list-nb");
		List<Resources> resList = FileResUtil.findResources(projectId);
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);// 项目信息
		List<Dictionary> projectFileList = DictUtil.dictChildren("projectFileName");

		// 投标人文件选择
		ProjectBidInfo projectBidInfo = new ProjectBidInfo();
		projectBidInfo.setProjectId(projectId);
		List<ProjectBidInfo> bidInfoList = this.projectInfoService.findProjectBidListByProjectId(null, projectBidInfo);

		//竞价公示暂停附件
		List<Resources> shotPauseResList=new ArrayList<>();
		List<ProjectPause> shotPauseList = this.profectPauseService.getPrjectPause(project.getId(), "0");
		for (ProjectPause pause : shotPauseList) {
			List<Resources> resourcesList = FileResUtil.findResources(pause.getId());
			shotPauseResList.addAll(resourcesList);
		}

		//中标公示暂停附件
		List<Resources> bidPauseResList=new ArrayList<>();
		List<ProjectPause> bidPauseList = this.profectPauseService.getPrjectPause(project.getId(), "1");
		for (ProjectPause pause : bidPauseList) {
			List<Resources> resourcesList = FileResUtil.findResources(pause.getId());
			bidPauseResList.addAll(resourcesList);
		}

		mv.addObject("bidInfoList", bidInfoList);
		mv.addObject("projectId", projectId);
		mv.addObject("project", project);
		mv.addObject("resList", resList);
		mv.addObject("shotPauseResList", shotPauseResList);
		mv.addObject("bidPauseResList", bidPauseResList);
		mv.addObject("projectFileList", projectFileList);
		if (userRole != null&&centerAuditor==null&&bizmanageRole==null) {// 不为空，是采购人,且不是项目怒负责人和业务管理员
			mv.addObject("isBuyer", true);
		}
		return mv;
	}


	/**
	 * @description归档 文件导出下载
	 * @author shy
	 * @date 2016年9月9日
	 * @param resId
	 * @param response
	 * @param request
	 * @throws Exception
	 * @throws Exception
	 */
	@RequestMapping("/leader/exportAllFile")
	public void exportAllFile(String resId, HttpServletResponse response, HttpServletRequest request, String projectId,
							  String[] resIds, String[] bidderIds) throws Exception {
		List<File> tenpFileList = new ArrayList<File>();// 临时问价集合
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);
		List<String> resIdsList = new ArrayList<String>();
		if (resIds != null) {
			resIdsList = Arrays.asList(resIds);
		}
		List<Resources> resList = FileResUtil.findResources(projectId);
		// 1获取项目相关的资料
		List<File> fileList = new ArrayList<File>();
		List<String> fileNameList = new ArrayList<String>();
		for (Resources res : resList) {
			if (resIdsList.contains(res.getFunctionFlog().toString())) {// 选择了
				// 获取此资源文件的数据字典信息
				int fileIndex = DictUtil.dict("projectFileName", res.getFunctionFlog() + "").getDisSort();// 排序值
				// 打包
				// 获取文件服务器真实路径
				String fileRealPath = res.getFilePath() + File.separator + res.getId() + res.getExeName();
				String filePath = request.getSession().getServletContext().getRealPath("/");
				fileRealPath = filePath + "file_resource" + fileRealPath;
				// 文件上传的真实名
				fileNameList.add(fileIndex + "-" + res.getOldName());
				File file = new File(fileRealPath);
				fileList.add(file);
			}
		}

		// 1.2、获取竞价公示+暂停资料
		if (resIdsList.contains(BID_PAUSE)) {
			List<ProjectPause> shotPauseList = this.profectPauseService.getPrjectPause(project.getId(), "0");
			for (ProjectPause pause : shotPauseList) {
				List<Resources> resourcesList = FileResUtil.findResources(pause.getId());
				for (Resources res : resourcesList) {
					// 打包
					// 获取此资源文件的数据字典信息
					int fileIndex = DictUtil.dict("projectFileName", res.getFunctionFlog() + "").getDisSort();// 排序值
					// 获取文件服务器真实路径
					String fileRealPath = res.getFilePath() + File.separator + res.getId() + res.getExeName();
					String filePath = request.getSession().getServletContext().getRealPath("/");
					fileRealPath = filePath + "file_resource" + fileRealPath;
					// 文件上传的真实名
					fileNameList.add(fileIndex + "-" + res.getOldName());
					File file = new File(fileRealPath);
					fileList.add(file);
				}
			}
		}

		// 1.3、获取竞价中标暂停资料
		if (resIdsList.contains(HIT_PAUSE)) {
			// 1、中标公示暂停信息
			List<ProjectPause> bidPauseList = this.profectPauseService.getPrjectPause(project.getId(), "1");
			for (ProjectPause pause : bidPauseList) {
				List<Resources> resourcesList = FileResUtil.findResources(pause.getId());
				for (Resources res : resourcesList) {
					// 打包
					// 获取此资源文件的数据字典信息
					int fileIndex = DictUtil.dict("projectFileName", res.getFunctionFlog() + "").getDisSort();// 排序值
					// 获取文件服务器真实路径
					String fileRealPath = res.getFilePath() + File.separator + res.getId() + res.getExeName();
					String filePath = request.getSession().getServletContext().getRealPath("/");
					fileRealPath = filePath + "file_resource" + fileRealPath;
					// 文件上传的真实名
					fileNameList.add(fileIndex + "-" + res.getOldName());
					File file = new File(fileRealPath);
					fileList.add(file);
				}
			}
		}

		// 1.4、获取质疑投诉资料
		if (resIdsList.contains(OPPUGN_PAUSE)) {
			List<WebContent> webContentList = this.webContentService.findListByProjectId(project.getId());
			for (WebContent web : webContentList) {
				List<Resources> resourcesList = FileResUtil.findResources(web.getId());
				for (Resources res : resourcesList) {
					// 获取此资源文件的数据字典信息
					int fileIndex = DictUtil.dict("projectFileName", res.getFunctionFlog() + "").getDisSort();// 排序值
					// 打包
					// 获取文件服务器真实路径
					if (OPPUGN_PAUSE.equals(res.getFunctionFlog().toString())) {// 质疑投诉资料
						String fileRealPath = res.getFilePath() + File.separator + res.getId() + res.getExeName();
						String filePath = request.getSession().getServletContext().getRealPath("/");
						fileRealPath = filePath + "file_resource" + fileRealPath;
						// 文件上传的真实名
						fileNameList.add(fileIndex + "-" + res.getOldName());
						File file = new File(fileRealPath);
						fileList.add(file);
					}
				}
			}
		}
		// 1.5、获取变更公告资料
		if (resIdsList.contains(EDITPUBLISH)) {
			List<WebContent> webContentList = this.webContentService.findListByProjectId(project.getId());
			for (WebContent web : webContentList) {
				List<Resources> resourcesList = FileResUtil.findResources(web.getId());
				for (Resources res : resourcesList) {
					// 获取此资源文件的数据字典信息
					int fileIndex = DictUtil.dict("projectFileName", res.getFunctionFlog() + "").getDisSort();// 排序值
					// 打包
					// 获取文件服务器真实路径
					if (EDITPUBLISH.equals(res.getFunctionFlog().toString())) {// 变更公告
						String fileRealPath = res.getFilePath() + File.separator + res.getId() + res.getExeName();
						String filePath = request.getSession().getServletContext().getRealPath("/");
						fileRealPath = filePath + "file_resource" + fileRealPath;
						// 文件上传的真实名
						fileNameList.add(fileIndex + "-" + res.getOldName());
						File file = new File(fileRealPath);
						fileList.add(file);
					}
				}
			}
		}

		// 2、获取投标人资料
		if (bidderIds != null) {
			for (String bidderId : bidderIds) {
				List<Resources> bidderResList = FileResUtil.findResources(projectId + "," + bidderId);
				RegisterUser registerUser = this.projectInfoService.get(RegisterUser.class, bidderId);
				List<File> bidderFileList = new ArrayList<File>();
				List<String> bidderFileNameList = new ArrayList<String>();
				for (Resources res : bidderResList) {
					// 打包
					// 获取文件服务器真实路径
					String fileRealPath = res.getFilePath() + File.separator + res.getId() + res.getExeName();
					String filePath = request.getSession().getServletContext().getRealPath("/");
					fileRealPath = filePath + "file_resource" + fileRealPath;
					// 文件上传的真实名
					bidderFileNameList.add(res.getOldName());
					File file = new File(fileRealPath);
					bidderFileList.add(file);
				}
				if (registerUser != null) {
					File tempFile = File.createTempFile(registerUser.getLoginName() + System.currentTimeMillis(),
							".zip");// 打包的投标人资料(临时文件,保证文件名长度大于3个)
					// File tempFile = new
					// File("G:/"+registerUser.getLoginName()+".zip");//打包的投标人资料
					ZipArchiveOutputStream zos = new ZipArchiveOutputStream(tempFile);
					// 打包文件
					BatchZipDownload.zip(bidderFileList, bidderFileNameList, "", zos);
					// 将打包的zip加入总包里
					fileList.add(tempFile);
					fileNameList.add(registerUser.getLoginName() + ".zip");
					// 将临时文件存入临时文件集合中
					tenpFileList.add(tempFile);
					if (zos != null) {
						zos.close();
					}
				}
			}

		}

		ZipArchiveOutputStream zos = null;
		OutputStream os = null;
		String zipName = project.getName() + ".zip";
		try {

			zos = new ZipArchiveOutputStream(response.getOutputStream());
			os = response.getOutputStream();

			// 下载
			response.reset();
			response.setHeader("Content-disposition",
					"attachment;filename=\"" + new String(zipName.getBytes("gb2312"), "ISO-8859-1") + "\"");
			response.setContentType("application/octet-stream");

			// 整体打包文件
			BatchZipDownload.zip(fileList, fileNameList, "", zos);

		} catch (Exception e) {
			System.err.println(e);
		} finally {
			if (zos != null) {
				try {
					os.flush();
					zos.flush();
					zos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// 删除临时文件
			for (File file : tenpFileList) {
				file.delete();
			}
		}

	}




}
